var mapTemplateURL="http://ogc.gbif.org/wms?request=GetMap&bgcolor=0x000000&styles=,&layers=gbif:country_fill,gbif:tabDensityLayer&srs=EPSG:4326&filter=()(%3CFilter%3E%3CPropertyIsEqualTo%3E%3CPropertyName%3Eurl%3C/PropertyName%3E%3CLiteral%3E%3C!%5BCDATA%5Bhttp%3A%2F%2Fdata.gbif.org%2Fmaplayer%2Ftaxon%2FGBIF_NUB_ID%5D%5D%3E%3C/Literal%3E%3C/PropertyIsEqualTo%3E%3C/Filter%3E)&width=300&height=150&Format=image/png&bbox=-180,-90,180,90";
var userPrefs;

function str(x) {
	if(x!=null && x.length > 0) return x;
	return '';
}


function linkDataPortal(id){
    var murl = mapTemplateURL.replace("GBIF_NUB_ID",id);
    $("#occurrences a").attr("href","http://data.gbif.org/species/"+id);
    $("#occurrences img").attr("src",murl);
}
function addFlickrImages(canonicalName){
  $("#flickr").empty();
  flickrSearch(canonicalName, false, function(flickrResponse){
      $.each(flickrResponse.photos.photo, function(i,p){
          $("#flickr").append("<div><a class='noline' id='"+flickrWebPageUrl(p)+"' href='"+flickrWebPageUrl(p)+"' target='_blank'><img src='"+flickrPhotoUrl(p,'s')+"'/></a> </div>");
      });
      if (flickrResponse.photos.length==0){
          $("#flickr").append("<div>No images found</div>");
      }
  });
}


function flickrPhotoUrl(photo,size){
    return "http://farm"+photo.farm+".static.flickr.com/"+photo.server+"/"+photo.id+"_"+photo.secret+"_"+size+".jpg";
}
function flickrWebPageUrl(photo){
    return "http://www.flickr.com/photos/"+photo.owner+"/"+photo.id;
}
function flickrSearch(q, includeCommercial, callback){
	var license="";
	if (includeCommercial){
		license="";
	}else{
		license="&license=1,2,3,4,5,6,7,8";
	}
    var url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&per_page=49&text="+escape(q)+license+"&api_key=bbd4239d4609542375990a33a098ee44&format=json&jsoncallback=?";
    $.getJSON(url, callback);
}
function storePhotoUrl(usageId, url, successCallback){
    $.ajax({
      type: "GET",
      url:  service+"image",
      data: { id:usageId, url:url },
      dataType: "jsonp",
      success: successCallback,
      error: function (xhr, textStatus, errorThrown) {
          alert( "Error saving image: " + textStatus );
      }
    });
}

function initCollapsable(){
    $("div.collapsed ul").hide();
    $("div.collapsable").prepend('<div class="toggler"><span class="btn TGshow">show</span><span class="btn TGhide">hide</span></div>');
    $("span.TGshow").hide();
    $("div.collapsed span.TGhide").hide();
    $("div.collapsed span.TGshow").show();
    $(".TGshow").click(function(e) {
        $("ul",$(this).parent().parent()).show();
        $(this).hide();
        $(".TGhide",$(this).parent()).show();
    })
    $(".TGhide").click(function(e) {
        $("ul",$(this).parent().parent()).hide();
        $(this).hide();
        $(".TGshow",$(this).parent()).show();
    })
}
function isTrueOrNull(x){
	if (x==null || x==true){
		return true;
	}
	return false;
}
function initToc(){
	//console.log(userPrefs);
	// restore cookie state
	if (userPrefs.showToc){
        $("#toc").show();
	    $("#tocMini").hide();
	}else{
        $("#toc").hide();
	    $("#tocMini").show();
	}
    $("#tocMini").click(function(e) {
    	e.preventDefault();
    	// minimize TOC
        $("#toc").show(400);
	    $("#tocMini").hide();
	    userPrefs.showToc=true;
	    setUserPrefCookie();
    });
    $("#toc h2").click(function(e) {
    	e.preventDefault();
    	// minimize TOC
        $("#toc").hide(500);
	    $("#tocMini").show();
	    userPrefs.showToc=false;
	    setUserPrefCookie();
    });
    $("#content h1, #content h2, #content h3").each(function(index) {
    	var anchor="chapter"+(index+1);
	    $("#toc ol:first").append('<li><a href="#'+anchor+'">'+$(this).text()+'</a></li>'); 
	    $(this).prepend('<a name="'+anchor+'"></a>'); 
	});
}

function readUserPrefCookie(){
	var cookieData = $.cookie("prefs");
	userPrefs = cookieData ? JSON.parse(cookieData) : {"showToc":true, "showBetaWarning":true};
}
function setUserPrefCookie(){
	// expiration in days
    var options = { path: '/', expires: 1 }; 
	var cookieData = JSON.stringify(userPrefs);
	$.cookie("prefs", cookieData, options);
}

function show(obj, indent)
{
  if (indent == null) indent = "";
  if (obj instanceof Array){
	 var result = indent + "[\n";
	  for (var property in obj){
	    result += indent + show(obj[property], indent+"  ") +",";
		}
		return result.replace(/,$/, "\n") + indent + "]";
	}else{
	 var result = indent + "{\n";
	 for (var property in obj)
	 {
	   var value = obj[property];
	   if (typeof value == 'string')
	     value = "'" + value + "'";
	   else if (typeof value == 'object')
	   {
	     if (value instanceof Array)
	     {
	       // Just let JS convert the Array to a string. Works only for primitives...
	       value = show(value,indent);
	     }
	     else
	     {
	       var od = show(value, indent+"  ");
	       value = "\n" + indent + "{\n" + od + "\n" + indent + "}";
	     }
	   }
	   result += indent + "'" + property + "' : " + value + ",\n";
	 }
	 return result.replace(/,\n$/, "\n")+indent + "}";
	}
}
